layui.define(function(exports){ //提示：模块也可以依赖其它模块，如：layui.define('layer', callback);
  var obj = {};
exports('roletrees', obj);
});
var $ = layui.$
 var roletrees = {
    // 方法1
    render:function($this, options) {
    //初始化调用
        // if(options.isreload){
        //   $('#'+$this).html('');
        // }
    //当前对象
        var that=this;
        var _thisgrid = $this;
        //获取表格参数
        var _thisOptions = options ? options : "";
        if (!_thisOptions) {
            layer.alert("请设置参数数据!")
            return
        }

        //获取默认宽度
        // var width = _thisOptions ? _thisOptions.width : 666;
        // //默认高度
        // var height = _thisOptions ? _thisOptions.height : 666;
        //数据地址
        var dataUrl = _thisOptions.dataUrl ? _thisOptions.dataUrl : '';
        //已选数据是否单选
        var isCheck = _thisOptions.isCheck ? _thisOptions.isCheck : false;
        //是否显示已选中的数据
        var isSelectedRadio = _thisOptions.isSelectedRadio ? _thisOptions.isSelectedRadio : false;
        //是否展开
        var isOpen = _thisOptions.isOpen ? _thisOptions.isOpen : false;
        //显示操作列表
        var operate = _thisOptions.operate ? _thisOptions.operate : false;
        //复选框名称
        var Checkname = _thisOptions.Checkname ? _thisOptions.Checkname : 'layuiTreeCheck_';
        //id名称
        var idname = _thisOptions.idname ? _thisOptions.idname : false;
        //pid名称
        var pidname = _thisOptions.pidname ? _thisOptions.pidname : false;
        //判断
        if(!idname && !pidname){
            layer.alert("请设置id及父id字段名!");
            return
        }
        if (dataUrl != undefined && dataUrl != "") {
         //如果是从后台获取数据
            data = that.getDataByUrl(dataUrl);
        } else {
            layer.alert("请设置数据加载路径!");
            return
        }
        if(!data){
           // layer.alert("数据为空!")
           return
        }else{
           val=that.dealdata(data,idname,pidname);
           val.forEach(v => {
             that.createLi(v,idname,pidname,_thisgrid,isCheck,isOpen,Checkname);
            })
           that.addbutton(_thisgrid);
        }
         
        //点击获取下页
        $(document).on('click',$('div'),function(e){
            if(e.target.dataset.id){
              that.hideSubLi(data,_thisgrid,idname);   //隐藏所有子div
            }
            onedata=that.choosedata(data,(e.target.dataset.id),idname);
            //点击显示子页
             onedata.forEach((items) => { 
                  $('input:checkbox[name='+Checkname+items[pidname]+']').prop("checked", true);
                  $('input:checkbox[name='+Checkname+items[idname]+']').prop("checked", true); 
                   that.showSubLi(_thisgrid,items[idname]);  //显示指定子div
               })
         })
        //选中复选框
        $(document).on('click','input[type="checkbox"]',function(e){
             // console.log(e);
            if(e.target.dataset.skin){
              that.hideSubLi(data,_thisgrid,idname);   //隐藏所有子div
            }
             onedata=that.choosedata(data,$(this).val(),idname);
             if($(this).is(':checked')==true){
               onedata.forEach((items) => {
                  $('input:checkbox[name='+Checkname+items[pidname]+']').prop("checked", true);
                   that.showSubLi(_thisgrid,items[idname]);  //显示指定子div
               })
             }else{
               ponedata=that.choosedata(data,$(this).val(),pidname);
               ponedata.forEach((items) => {
                  $('input:checkbox[name='+Checkname+items[idname]+']').prop("checked", false);
              });
               //取消下页选中状态
               onedata.forEach((items) => {
                 if(items.operate){
                      (eval(items.operate)).forEach((item) => {
                      $('input:radio[name=radio'+items[idname]+']').prop("checked", false); 
                     })
                   }
                });  
             }
           })

        //选中单选框
        $(document).on('click','input[type="radio"]',function(e){
             $('input:radio[name=radio'+$(this).attr('data-role')+']').prop("checked", false);;
             $(this).prop("checked", true);
           })

        //提交按钮
        $(document).on('click','.layui-btn-trees', function(){
            // var chk_value=[];//定义一个数组
            var operate_value=[];
            data.forEach((items) => {
                  // var chk_map ={};//定义一个map
                  if($('input:checkbox[name='+Checkname+items[idname]+']:checked').val()==items[idname]){
                      // chk_map['module_id']=items[idname];
                      var operates={};
                      if($('input:radio[name=radio'+(items[idname])+']:checked')){
                                // if($('input:radio[name=radio'+(items[idname])+']').val()==item.rid){
                                    operates['module_id']=items[idname];
                                    operates['role_id']=$('input:radio[name=radio'+(items[idname])+']:checked').val();
                                // };
                                operate_value.push(operates); 
                       }
                      // chk_value.push(chk_map); 
                   }; 
               });
            // chk_value=JSON.stringify(chk_value);
            operate_value=JSON.stringify(operate_value);
            // $('#check_id').val(chk_value);
            $('#operate').val(operate_value);
            $('#treebut').show();
        })
        
    },

    //获取数据
    getDataByUrl : function(dataurl) {
        // console.log(dataurl)
        var data='';
            $.ajax({
                url: dataurl,
                async:false,
                type: 'get',
                dataType: "json",
                success:function(R){
                if (R.code == 200) {
                    data = R.data;
                } else {
                     data = {};
                }

                },
                error: function (R) {
                  // alert('failure to send to database');
                }
            });
            // console.log(data)
            return data;
        },
    // 处理数据
    //1、 先把数据处理成map
    dealdata:function(data,idname,pidname){
        // 数据
        const map = {};
        const val = [];
        data.forEach((item) => {
          map[item[idname]] = item;
        });
       // 2、遍历之后，形成树形结构
        data.forEach((item) => {
        const parent = map[item[pidname]];
          if (parent) {
               (parent.children || (parent.children = [])).push(item);
             } else {
                val.push(item);
             }
         });
         return val;
        },
    // 处理选中数据
    choosedata:function(data,id,name){
          const val = [];
              // try{
                 data.forEach((item) => {
                    if(item[name]==id){
                      val.push(item);
                     }
                 });
          return val;
        },
    //创建树形布局
    createLi:function(data,idname,pidname,thisgrid,isCheck,isOpen,Checkname) {
            // 父元素id
            const fid = thisgrid+`${data[pidname]}`;
            const div = $('#'+fid);
            
            if(data.children){
                $(document).on('click','.layui-tree-close'+data[idname],function (e) {  
                // console.log(e)      
                $('.show'+data[idname]).hide();
                $('.layui-i'+data[idname]).addClass("layui-icon-addition");
                $('.layui-i'+data[idname]).removeClass("layui-icon-subtraction");
                $('.layui-tree-close'+data[idname]).addClass("layui-tree-open"+data[idname]);
                $('.layui-tree-open'+data[idname]).removeClass("layui-tree-close"+data[idname]);
                    
                })
                $(document).on('click','.layui-tree-open'+data[idname],function (e) {  
                // console.log(e)      
                $('.show'+data[idname]).show();
                $('.layui-i'+data[idname]).addClass("layui-icon-subtraction");
                $('.layui-i'+data[idname]).removeClass("layui-icon-addition");
                $('.layui-tree-open'+data[idname]).addClass("layui-tree-close"+data[idname]);
                $('.layui-tree-open'+data[idname]).removeClass("layui-tree-open"+data[idname]);        
                })
               var span = '<span class="layui-tree-icon '+( isOpen ? " layui-tree-close"+data[idname] : " layui-icon-open"+data[idname])+'"><i class="layui-icon layui-i'+data[idname]+ ( isOpen ? " layui-icon-subtraction" : " layui-icon-addition") +'"></i></span>';
            }else{
               var span = '<span class="layui-tree-iconClick"><i class="layui-icon layui-icon-file"></i></span>';
            };
            
            var checkbox = isCheck ? '<input type="checkbox" name="'+ (Checkname+data[idname])+'" class="layuiTreeCheck" data-skin="primary" '+ (data.checked ? "checked" : "") +' value="'+ data[idname] +'">' : '';

            var childrendiv=$('<div></div>'); //创建一个div
            childrendiv.attr('id', thisgrid+`${data[idname]}`); //设置id
            childrendiv.attr('data-id', `${data[idname]}`); //给data-id值
            if(data.children){
            childrendiv.addClass('treeItem');   //添加css样式
            }else{
            childrendiv.addClass('treeItem layui-tree-left show'+data[pidname]);
            }
            childrendiv.css({cursor:'pointer',color:'#666'});
            childrendiv.html(span+checkbox+data.title);
            if(data[pidname]>0){
             div.append(childrendiv);    
            }else{
             $('#'+thisgrid).append(childrendiv);   
            } 
            // console.log(data)
            if(data.operate){
                this.createSubLi(data,idname,thisgrid,isCheck,Checkname);
            }
            if (data.children) {
                data.children.forEach(d => {
                    this.createLi(d,idname,pidname,thisgrid,isCheck,isOpen,Checkname);
                });
            }

        },
    //创建操作布局
    createSubLi:function(subdata,idname,thisgrid,isCheck,Checkname) {
            const div = $('#'+thisgrid).parent("div");
            var content='';
            if(subdata.operate){
            (eval(subdata.operate)).forEach((item) => {
               content +='<li><span class="layui-tree-iconClick"><i class="layui-icon layui-icon-file"></i></span>';
               content += isCheck ? '<input type="radio" name="radio'+(subdata[idname])+'" class="layuiTreeCheck" '+ (item.checked ? "checked" : "") +' data-role="'+(subdata[idname])+'" value="'+ item.rid+/*'@'+subdata[idname]+*/'">' : '';
               content +=item.name;
               content +='</li>';
            })
            }

            var childrendiv=$('<div></div>'); //创建一个父div
            childrendiv.attr('id', thisgrid+`sub`+subdata[idname]); //给父div设置id
            childrendiv.addClass('treesub');   //添加css样式
            childrendiv.css({display:'none'});   //添加css样式 
            childrendiv.html(content);       
            div.append(childrendiv); 
        },
    //隐藏所有子div
    hideSubLi:function(data,thisgrid,idname) {
            data.forEach((items)=>{
             $("#"+thisgrid+`sub`+items[idname]).hide();
             $("#"+thisgrid+items[idname]).css({color:'#666'});    
            }) 
        },
    //显示指定div
    showSubLi:function(thisgrid,id) {
            $("#"+thisgrid+`sub`+id).css({display:'block'});
            $("#"+thisgrid+id).css({color:'#1e9fff'});
        },
    // 创建按钮
    //显示指定div
    addbutton:function(thisgrid) {
            const div = $('#'+thisgrid).parent("div");
            var content='';
            content +='';
            content +='<button type="button" class="layui-btn-trees">选择数据</button>';
            content +='<button class="layui-btn" type="button" lay-submit lay-filter="submit" style="display: none;" id="treebut">保存数据</button>';
            content +='';
            var childrendiv=$('<div></div>'); //创建一个父div
            childrendiv.addClass('treesubbutton');   //添加css样式
            childrendiv.html(content);       
            div.append(childrendiv); 
        },
};
